package org.lq.er.view.Information;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

import org.lq.er.entity.Exam_information;
import org.lq.er.entity.Score_info;
import org.lq.er.entity.Student;
import org.lq.er.entity.Subject;
import org.lq.er.service.Exam_informationService;
import org.lq.er.service.Score_infoService;
import org.lq.er.service.StudentService;
import org.lq.er.service.SubjectService;
import org.lq.er.service.impl.Exam_informationServiceImpl;
import org.lq.er.service.impl.Score_infoServiceImpl;
import org.lq.er.service.impl.StudentServiceImpl;
import org.lq.er.service.impl.SubjectServiceImpl;

import javax.swing.JLabel;
import javax.swing.JOptionPane;

import java.awt.Font;
import java.awt.SystemColor;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.DefaultComboBoxModel;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.Random;
import java.awt.event.ActionEvent;
import java.awt.Color;
/**
 * 报名视图
 * @author 韩伟伟
 *
 * @package org.lq.er.view.Information
 */
public class V_Apply extends JFrame {

	private JPanel contentPane;
	private JTextField text_name;
	private JTextField text_grade;
	private JTextField text_card_id;
	private String [] arr;
	private static Exam_informationService<Exam_information> ps = new Exam_informationServiceImpl();
	private Score_infoService ss = new Score_infoServiceImpl();
	private StudentService studentService = new StudentServiceImpl();
	private SubjectService subjectService = new SubjectServiceImpl();

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					V_Apply frame = new V_Apply();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public V_Apply() {
		setResizable(false);
		setTitle("等级考试报名系统");
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 484, 375);
		setLocationRelativeTo(null);
		contentPane = new JPanel();
		contentPane.setBackground(Color.white);
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		
		JPanel panel = new JPanel();
		contentPane.add(panel, BorderLayout.CENTER);
		panel.setLayout(null);
		
		JLabel lblNewLabel = new JLabel("报名");
		lblNewLabel.setForeground(SystemColor.textHighlight);
		lblNewLabel.setFont(new Font("宋体", Font.PLAIN, 25));
		lblNewLabel.setBounds(0, 0, 60, 29);
		panel.add(lblNewLabel);
		
		JPanel panel_1 = new JPanel();
		panel_1.setBounds(0, 26, 468, 311);
		panel.add(panel_1);
		panel_1.setLayout(null);
		
		JLabel lblNewLabel_1 = new JLabel("班级：");
		lblNewLabel_1.setFont(new Font("宋体", Font.PLAIN, 14));
		lblNewLabel_1.setBounds(160, 25, 48, 32);
		panel_1.add(lblNewLabel_1);
		
		text_name = new JTextField();
		text_name.setBounds(53, 31, 80, 21);
		panel_1.add(text_name);
		text_name.setColumns(10);
		
		JLabel lblNewLabel_1_1 = new JLabel("姓名：");
		lblNewLabel_1_1.setFont(new Font("宋体", Font.PLAIN, 14));
		lblNewLabel_1_1.setBounds(10, 28, 48, 32);
		panel_1.add(lblNewLabel_1_1);
		
		text_grade = new JTextField();
		text_grade.setColumns(10);
		text_grade.setBounds(216, 31, 80, 21);
		panel_1.add(text_grade);
		
		JLabel lblNewLabel_1_2 = new JLabel("科目：");
		lblNewLabel_1_2.setFont(new Font("宋体", Font.PLAIN, 14));
		lblNewLabel_1_2.setBounds(318, 25, 48, 32);
		panel_1.add(lblNewLabel_1_2);
		
		JComboBox subject = new JComboBox();
		List<Subject> list = subjectService.findAll();
		System.out.println(list);
		arr = new String[list.size()];
		for (int i = 0; i < arr.length; i++) {
			arr[i] = list.get(i).getSubjectName();
		}
		subject.setModel(new DefaultComboBoxModel(arr));
		subject.setBounds(366, 30, 80, 23);
		panel_1.add(subject);
		
		JLabel lblNewLabel_1_3 = new JLabel("身份证号：");
		lblNewLabel_1_3.setFont(new Font("宋体", Font.PLAIN, 14));
		lblNewLabel_1_3.setBounds(10, 98, 80, 32);
		panel_1.add(lblNewLabel_1_3);
		
		text_card_id = new JTextField();
		text_card_id.setBounds(87, 104, 209, 21);
		panel_1.add(text_card_id);
		text_card_id.setColumns(10);
		
		JButton btn_submit = new JButton("提交");
		btn_submit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
//-------------------添加业务-----------------------	
				String card_id = text_card_id.getText();
				System.out.println(card_id+"*****************");
				int subNum = toNum(subject.getSelectedItem().toString());
				Exam_information em = new Exam_information();
				em.setStu_id(card_id);
				em.setExam_position_id(0);
				em.setSubject_id(subNum);
				em.setSeat_num(0);
				Student student = studentService.getByCard_id(card_id);
				String stu_id = String.valueOf(student.getStu_no());
				Score_info score_info = ss.getByStu_id(stu_id);
				System.out.println(score_info);
				Subject sub = subjectService.findById(subNum);
				int cost = sub.getCost();
				//  初始化空成绩
				if(score_info == null) {
					score_info = new Score_info();
					score_info.setStu_id(stu_id);
					score_info.setSubject_id(subNum);
					score_info.setScore(0);
					score_info.setStatus(1);
					ss.save(score_info);
				}
				Exam_information emCheck = (Exam_information) ps.getByStu_Id(card_id);
				// 判断学生考试信息是否空;非空,更新;否则添加
				if (emCheck != null) {
					if (!"".equals(card_id)&&ps.update(emCheck)) {
						Score_info score = ss.getByStu_id(stu_id);
						// 判断学生是否缺考
						if (score_info.getStatus() == 1) {
							emCheck.setStatus_check(1);
							int num = JOptionPane.showConfirmDialog(V_Apply.this, "是否缴费"+cost+"元?", "提示",JOptionPane.INFORMATION_MESSAGE);
							// 判断学学生是否缴费,是即分配考场
							if (num == 0) {
								emCheck.setExam_position_id(getRandom(1));
								emCheck.setSeat_num(randomArray(1, 30, 1));
								emCheck.setStatus_pay(1);
								System.out.println(emCheck);
								ps.update(emCheck);
								JOptionPane.showMessageDialog(V_Apply.this, "报名成功！", "提示", JOptionPane.INFORMATION_MESSAGE);
							} else if(num == 1){
								JOptionPane.showMessageDialog(V_Apply.this, "请稍后缴费！", "提示", JOptionPane.INFORMATION_MESSAGE);
							} else {
								emCheck.setExam_position_id(0);
								emCheck.setStatus_pay(0);
								ps.update(emCheck);
								JOptionPane.showMessageDialog(V_Apply.this, "报名失败！", "提示", JOptionPane.ERROR_MESSAGE);
							}
						} else {
							emCheck.setStatus_check(0);
							ps.update(emCheck);
							JOptionPane.showMessageDialog(V_Apply.this, "您缺考了!无法报名", "提示", JOptionPane.ERROR_MESSAGE);
						}
					}else {
						JOptionPane.showMessageDialog(V_Apply.this, "提交失败,请输入完整信息！", "错误", JOptionPane.ERROR_MESSAGE);
					}
				} else {
					if (!"".equals(card_id)&&ps.save(em)) {
						Exam_information updateEm =  ps.getByStu_Id(card_id);
						if (score_info.getStatus() == 1) {
							updateEm.setStatus_check(1);
							int num = JOptionPane.showConfirmDialog(V_Apply.this, "是否缴费"+cost+"?", "提示",JOptionPane.INFORMATION_MESSAGE);
							if (num == 0) {
								updateEm.setExam_position_id(getRandom(1));
								updateEm.setSeat_num(randomArray(1, 30, 1));
								updateEm.setStatus_pay(1);
								ps.update(updateEm);
								JOptionPane.showMessageDialog(V_Apply.this, "报名成功！", "提示", JOptionPane.INFORMATION_MESSAGE);
							} else if(num == 1){
								JOptionPane.showMessageDialog(V_Apply.this, "请稍后缴费！", "提示", JOptionPane.INFORMATION_MESSAGE);
							} else {
								updateEm.setExam_position_id(0);
								updateEm.setStatus_pay(0);
								ps.update(updateEm);
								JOptionPane.showMessageDialog(V_Apply.this, "报名失败！", "提示", JOptionPane.ERROR_MESSAGE);
							}
						} else {
							em.setStatus_check(0);
							ps.update(em);
							JOptionPane.showMessageDialog(V_Apply.this, "您缺考了!无法报名", "提示", JOptionPane.ERROR_MESSAGE);
						}
					}else {
						JOptionPane.showMessageDialog(V_Apply.this, "提交失败,请输入完整信息！", "错误", JOptionPane.ERROR_MESSAGE);
					}
				}
				
				
			}
		});
		btn_submit.setBounds(76, 216, 93, 23);
		panel_1.add(btn_submit);
		
		JButton btn_reset = new JButton("重置");
		btn_reset.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				reset();
			}
		});
		btn_reset.setBounds(304, 216, 93, 23);
		panel_1.add(btn_reset);
	}
	
	public int toNum(String subName) {
		int num = 0;
		List<Subject> list = subjectService.findAll();
		for (Subject subject : list) {
			if (subName.equals(subject.getSubjectName())) {
				num = subject.getId();
			}
		}
		return num;
	}
	
	/**
	 * 	产生随机考试位置
	 */
	public static int getRandom(int len) {
		int digit = (int) Math.pow(10, len - 1);
        int rs = new Random().nextInt(digit * 10)+1;
        int num = rs;
        while(ps.getByExam_position_id(num)!=null) {
        	getRandom(1);
        }
        return num;
    }
	
	/**
	 * 	重置窗体里的数据
	 */
	public void reset() {
		text_name.setText("");
		text_grade.setText("");
		text_card_id.setText("");
	}
	/**
	 * 	座位号随机产生
	@param max 指定范围最大值　
	 * @param min 指定范围最小值      
	 * @param n 随机数个数    
	 */
	public static int randomArray(int min, int max, int n) {
		int num = 0;
		int len = max - min + 1; 
		if (max < min || n > len) {
			return num;
		} 
		// 初始化给定范围的待选数组
		int[] source = new int[len];
		for (int i = min; i < min + len; i++) {
			source[i - min] = i;
		}
		int[] result = new int[n];
		Random rd = new Random();
		int index = 0;
		for (int i = 0; i < result.length; i++) {
			// 待选数组0到(len-2)随机一个下标
			index = Math.abs(rd.nextInt() % len--);
			// 将随机到的数放入结果集
			result[i] = source[index];
			num = result[i];
		}
		return num;
	}
	
}
